package com.lunwen.lunwen.api;

import com.lunwen.lunwen.bean.Result;
import com.lunwen.lunwen.config.ShiroUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

//import static com.sun.xml.internal.ws.spi.db.BindingContextFactory.LOGGER;

@Controller
@RequestMapping("api")
public class LoginController {

    @RequestMapping("/userlogin")
    @ResponseBody
    public Result userLogin (
            @RequestParam(value = "username") String userName,
            @RequestParam(value = "password") String passWord
    ){
        System.out.println(userName+" "+passWord);
        Result result = new Result();
        try{
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
            subject.login(token);
            System.out.println("getSession:"+subject.getSession().getId());
            System.out.println("登录成功");
            result.setCode("200");
            result.setMessage("登陆成功！");
            result.setData((subject.getSession().getId()).toString());
            return result;
        } catch (Exception e) {
            System.out.println(e.toString());
            Date date = new Date();
            result.setData(date);
            result.setCode("201");
            result.setMessage("登录失败！");
            return result;
        }
    }

    /**
     * 退出登陆
     */
    @RequestMapping("/logout")
    @ResponseBody
    public Result logout()
    {
        Result result = new Result();
        ShiroUtils.logout();
        System.out.println("退出登录成功");
        result.setCode("200");
        result.setMessage("退出登录成功！");
        return result;
    }

}
